import { Map, TileLayer, VectorLayer } from 'maptalks'
import { isobands, feature, featureCollection, geometry, bbox, intersect, union, isolines, point } from "@turf/turf";
import kriging from '@sakitam-gis/kriging';

const gridFeatureCollection = function (grid) {
  var i, j, x, y, z
  var n = grid.data.length // 列数
  var m = grid.data[0].length // 行数
  var pointArray = []
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      x = i * grid.width + grid.xlim[0]
      y = j * grid.width + grid.ylim[0]
      z = grid.data[i][j]
      pointArray.push(point([x, y], { value: z }))
    }
  }
  return pointArray
}

let map = new Map('map', {

  zoom: 5,
  center: [114, 30],
  baseLayer: new TileLayer('base', {
    urlTemplate: 'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
  })
})

const options = {
  cellSize: 1,
  weight: 4,
  zProperty: 'value'
}

let boundary = huabei
// const breaks = [-0.8, 0, 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2]
let breaks = [-0.8, -0.4, 0, 0.4, 0.8, 1.2, 1.6, 2, 2.4, 2.8, 50]
breaks = [0, 0.998, 0.9984, 0.9988, 0.9992, 0.9996, 1, 1.0004, 1.0008, 1.0012, 1.0016, 1.002, 2];//-0.8

// breaks = [1.0003, 1.0004, 1.0005, 1.0006, 1.0007, 1.0008, 1.0009, 1.0010, 1.0011, 1.0012, 1.0013, 1.0014, 1.005]


let colorList = [
  '#F03100',
  '#F03100',
  '#F09511',
  '#F0C70A',
  '#B7E000',
  '#11F70C',
  '#00F099',
  '#00F099',
  '#11F70C',
  '#B7E000',
  '#F0C70A',
  '#F09511',
  '#F03100',
  '#F03100',
]

colorList = [
  '#F03100',
  '#F03100',
  '#F09511',
  '#F0C70A',
  '#B7E000',
  '#11F70C',
  '#00F099',
  '#00F099',
  '#11F70C',
  '#B7E000',
  '#F0C70A',
  '#F09511',
  '#F03100',
  '#F03100'
]




let feaCol = undefined

sdata = ssdata[13]
sdata = sdata.map(i => [i.lon, i.lat, i.value])
let pointArray = sampleData1226[4].filter((ii) => ii.lat && ii.lon && ii.value && (ii.value > 0 && ii.value < 5))
let idwData = pointArray.map((i) => {
  return [i.lon, i.lat, Number(i.value)]
})

if (Array.isArray(idwData)) {
  feaCol = featureCollection(idwData.map(i => {
    const geo = {
      "type": "Point",

      "coordinates": [i[0], i[1]]
    };
    const fea = feature(geo)

    fea.properties[options.zProperty] = i[2] * 1

    return fea
  }))
}


// k

var values = [], lons = [], lats = [];
for (var i = 0; i < idwData.length; i++) {
  var item = idwData[i];
  values.push(item[2]);
  lons.push(item[0]);
  lats.push(item[1]);
}
var model = "exponential";
var sigma2 = 0, alpha = 100;
const variogram = kriging.train(values, lons, lats,
  model, sigma2, alpha);

const ex = bbox(boundary)

// 根据边界信息添加矩形坐标
const polygons = [[[ex[0], ex[1]], [ex[0], ex[3]], [ex[2], ex[3]], [ex[2], ex[1]]]]

// 使用边界信息的外切矩形重新生成grid
let kgrid = kriging.grid(polygons, variogram, (ex[2] - ex[0]) / 200)
let isogrid = gridFeatureCollection(kgrid)
let grid = featureCollection(isogrid)


// const grid = interpolate(feaCol, options.cellSize, {
//   gridType: 'point',
//   property: options.zProperty,
//   units: 'degrees',
//   weight: options.weight,
//   bbox: bbox(boundary)
// })

grid.features.map(i => {
  let val = i.properties['value']
  i.properties['value'] = (val * 1).toFixed(4)
  return i
})


const gridLayer = new VectorLayer('grid').addTo(map)
gridLayer.addGeometry(grid)
gridLayer.setStyle({
  symbol: {
    textName: '{value}',
    textSize: 12
  }
})
gridLayer.setZIndex(50)

const isobandsRes = isobands(grid, breaks, {
  zProperty: options.zProperty
})

let isolinesRes = isolines(grid, breaks, {
  zProperty: options.zProperty
})

const lineLayer = new VectorLayer('idwline', isolinesRes).addTo(map)


// 处理边界数据
const geoType = boundary.type
switch (geoType) {
  case 'FeatureCollection':
    let unionFea = boundary.features[0]
    for (let index = 1; index < boundary.features.length; index++) {
      const fea = boundary.features[index];
      unionFea = union(unionFea, fea)
    }

    boundary = unionFea
    break
  case 'Feature':
    break
  default:
    throw new Error('无效的边界数据')
}


const intersectRes = []
const z = options.zProperty
isobandsRes.features.forEach((isoFea) => {
  const pro = {}
  if (isoFea.properties && isoFea.properties[z] && isoFea.geometry.coordinates.length > 0) {// 校验插值后iso结果
    const intersection = intersect(isoFea, boundary)
    if (intersection) {
      intersection.properties[z] = isoFea.properties[z]
      intersectRes.push(intersection)
    }
  }
})


const idwLayer = new VectorLayer('idw').addTo(map)

idwLayer.addGeometry(intersectRes)





const stops = []
for (let index = 0; index < breaks.length - 1; index++) {
  stops.push([`${breaks[index]}-${breaks[index + 1]}`, `${colorList[index]}`])
}

console.log(stops);


idwLayer.setStyle({
  symbol: {
    polygonFill: {
      type: 'categorical',
      property: 'value',
      stops: stops,
      default: 'black'
    },
    lineColor: {
      type: 'categorical',
      property: 'value',
      stops: stops,
      default: 'black'
    },
    lineWdith: 1,
  }
})


// idwLayer.hide()
gridLayer.hide()
lineLayer.hide()



